package tech.xiaozai.rbac.security.authentication;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import tech.xiaozai.common.restful.RestResp;
import tech.xiaozai.rbac.security.JWTWorker;
import tech.xiaozai.rbac.security.config.KeyNameConfig;
import tech.xiaozai.rbac.security.MyUserDetails;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-23 11:09
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JWTWorker jwtWorker;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //拿到登录成功后的用户对象
        MyUserDetails user = (MyUserDetails) authentication.getPrincipal();
        List<String> roldIds = new LinkedList<>();
        user.getAuthorities().forEach(r->{
            roldIds.add(r.getAuthority());
        });

        String token = jwtWorker.createToken(user.getId(), roldIds);
        Map<String,Object> data = new HashMap<>();
        data.put(KeyNameConfig.TOKEN_KEY, token);
        data.put(KeyNameConfig.USER_ID_KEY,user.getId());
        data.put(KeyNameConfig.ROLE_IDS_KEY,roldIds);
        data.put(KeyNameConfig.USERNAME_KEY,user.getUsername());

        RestResp<Map<String, Object>> ok = RestResp.ok(data);
        String jsonStr = JSONUtil.toJsonStr(ok);
        //response.setStatus(200);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonStr);
        response.getWriter().flush();
    }
}
